const {
  ActivityModel
} = require('../../../utils/activity-model.js')
const activityModel = new ActivityModel()
const {
  MemberModel
} = require('../../../utils/member-model.js');
var memberModel = new MemberModel();
var utils = require("../../../utils/util.js");
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    originMemberId: '', //发起会员id
    targetMemberId: '', //帮砍会员id
    targetMemberAvatar: '', //帮砍人头像
    nickName: '', //参与者姓名
    activityId: '', //活动id
    activityBargainStarterId: '', //发起id，帮砍必填
    productId: '', //商品id
    status: -1, //砍价状态：发起人角度 0 自砍 1 邀请好友 2 立即下单 3 已下单 4 已超时 5 支付成功 * 帮砍人角度 6 帮砍一刀 7 我要参与 8 看一看我的砍价 * 9 活动已结束 选购热销商品 10 无库存
    recordList: [], //砍价记录
    bargainShow: false, //砍价弹出层
    activityInfo: {},
    day: '0',
    hou: '00',
    min: "00",
    sec: "00",
    timerName: '', //计时器名字
    activityEnd: '', //活动结束时间
    originMemberAvatar: '', //参与者头像
    bargainResult: '0.00', //已砍金额
    balance: '0.00', //余额
    progressbar: 0,
    isBargain: false,
    prizeInfo: {},
    participationShow: false,
    authShow: false
  },

  /**
   *微信会员信息
   */
  getUserInfo: function () {
    var that = this;
    memberModel.userInfo({
      merchantId: wx.getStorageSync('merchantId')
    }).then(data => {
      wx.setStorageSync('memberId', data.memberId);
      that.setData({
        targetMemberId: data.memberId || "", //会员ID
        originMemberId: that.data.originMemberId ? that.data.originMemberId : data.memberId,
        targetMemberAvatar: data.avatarUrl || '', //砍价人头像
        nickName: data.nickname || ''
      }, function () {
        that.getGoodsDetails()
      });
    }).catch(err => {
      wx.showToast({
        title: `${err.error}`,
        icon: 'none',
        duration: 2000
      })
    })
  },

  /**
   * 商品详情
   */
  getGoodsDetails: function (type) {
    var that = this;
    activityModel.bargainGoodsDetail({
      originMemberId: that.data.originMemberId, //发起会员id
      targetMemberId: that.data.targetMemberId, //帮砍会员id
      activityId: that.data.activityId, //活动id
      activityBargainStarterId: that.data.activityBargainStarterId, //发起id，帮砍必填
      productId: that.data.productId //商品id
    }).then(data => {
      let status = false
      if (that.data.originMemberId == that.data.targetMemberId && data.success) {
        status = false
      } else if (that.data.originMemberId != that.data.targetMemberId && data.success) {
        status = true
      } else {
        status = false
      }
      that.setData({
        isBargain: false,
        participationShow: false,
        status: data.status,
        activityBargainStarterId: data.activityBargainStarterId,
        activityInfo: data || {},
        bargainShow: (data.status == 0 || data.status == 6 || status) && type != 1 ? true : false,
        activityEnd: data.endTime.replace(/-/g, '/') || ''
      }, function () {
        let nowTime = new Date().getTime(); //现在时间（时间戳）
        let roundEndTime = new Date(that.data.activityEnd).getTime();
        if (that.data.activityEnd != "" && that.data.status != 9 && roundEndTime > nowTime) {
          that.countDown()
        }
        if (data.activityBargainStarterId && data.activityBargainStarterId != '' && data.status && data.status != 9) {
          that.getBargainGoodsRecord()
        }
        if (that.data.originMemberId == that.data.targetMemberId) {
          that.setData({
            originMemberAvatar: that.data.targetMemberAvatar || ''
          })
        }
      })
    }).catch(err => {
      wx.showToast({
        title: `${err.error}`,
        icon: 'none',
        duration: 2000
      })
    })
  },

  /**
   * 砍价记录
   */
  getBargainGoodsRecord: function () {
    activityModel.bargainGoodsRecord({
      originMemberId: this.data.originMemberId, //发起会员id
      activityBargainStarterId: this.data.activityBargainStarterId, //发起id
    }).then(data => {
      let balance = parseFloat(this.data.activityInfo.price - data.bargainResult).toFixed(2)
      let progressbar = 0
      if (this.data.activityInfo.success) {
        progressbar = 100
      } else {
        if (this.data.status == 1 || this.data.status == 6 || this.data.status == 7 || this.data.status == 8 || this.data.status == 10) {
          console.log(balance)
          //砍价比例=砍掉金额/（总价-砍到金额）*100%
          progressbar = data.bargainResult / (this.data.activityInfo.price - this.data.activityInfo.floorPrice) * 100 || 0
        } else if (this.data.status == 2 || this.data.status == 3 || this.data.status == 4 || this.data.status == 5) {
          progressbar = 100
        }
      }
      const recordData = (data.bargainRecordList || []).map(item => {
        return {
          ...item,
          bargainAmount: utils.formatCurrency(item.bargainAmount, 1) || '0.00',
        }
      })
      this.setData({
        recordList: recordData || [], //砍价记录
        originMemberAvatar: data.originMemberAvatar || '', //参与者头像
        bargainResult: data.bargainResult || '0', //已砍金额
        balance: balance || '0.00',
        progressbar: progressbar
      })
    }).catch(err => {
      wx.showToast({
        title: `${err.error}`,
        icon: 'none',
        duration: 2000
      })
    })
  },
  /**
   * 砍价接口
   */
  getBargainGoodsReduce: function () {
    activityModel.bargainGoodsReduce({
      originMemberId: this.data.originMemberId, //发起会员id
      targetMemberId: this.data.targetMemberId, //发起id
      activityId: this.data.activityId, //活动id
      productId: this.data.productId, //商品id
      targetMemberAvatar: this.data.targetMemberAvatar, //帮砍人头像
      activityBargainStarterId: this.data.activityBargainStarterId, //发起id，帮砍必填
      targetMemberName: this.data.nickName //帮砍人名字
    }).then(data => {
      this.setData({
        isBargain: true,
        activityBargainStarterId: data.activityBargainStarterId,
        prizeInfo: data || {}
      })
    }).catch(err => {
      wx.showToast({
        title: `${err.error}`,
        icon: 'none',
        duration: 2000
      })
    })
  },
  //砍价
  userBargain: function () {
    this.getBargainGoodsReduce()
  },
  //跳转到首页
  goHome: function () {
    this.setTrackerLogInfo('已结束-选购热销商品按钮')
    wx.reLaunch({
      url: '/pages/index/index'
    })
  },
  //关闭弹出层
  closeDialog: function () {
    this.setData({
      bargainShow: false
    })
    if (this.data.isBargain) {
      this.getGoodsDetails()
    }
  },
  setBargain: function () {
    if (this.data.status == 0 || this.data.status == 6) {
      this.setData({
        bargainShow: true
      })
    } else if (this.data.status == 7) {
      this.setParticipationModel()
    } else if (this.data.status == 5 || this.data.status == 10) {
      wx.redirectTo({
        url: '/activityBargain/bargain/productList/index?activityId=' + this.data.activityId + '&shopId=' + this.data.activityInfo.shopId
      })
    } else if (this.data.status == 2 || this.data.status == 3 || this.data.status == 4) {
      wx.navigateTo({
        url: `/activityBargain/bargain/bargainOrder/index?currency=${encodeURIComponent(JSON.stringify(this.data.activityInfo))}`
      })
    }
    let source = this.data.status == 0 ? '自砍一刀' : this.data.status == 1 ? '召唤好友帮忙砍价按钮' : (this.data.status == 2 || this.data.status == 3 || this.data.status == 4) ? '立即下单' : this.data.status == 5 ? '继续选择其他商品砍价' : this.data.status == 6 ? '帮好友砍一刀按钮' : status == 7 ? '我要参与' : status == 8 ? '看一看我的砍价' : status == 10 ? '已售罄-查看其他热门砍价商品' : ''
    this.setTrackerLogInfo(source)
  },

  /**
   * 我要参与提示层
   */
  setParticipationModel() {
    this.setData({
      bargainShow: false,
      participationShow: true
    })
  },

  /**
   * 我要参与
   */
  goJoin() {
    wx.redirectTo({
      url: '/activityBargain/bargain/details/index?activityId=' + this.data.activityId + '&productId=' + this.data.productId + '&shareMemberId=' + this.data.targetMemberId
    })
  },
  closeParticipation() {
    this.getGoodsDetails(1)
    this.setData({
      participationShow: false
    })
  },
  // 倒计时
  countDown: function () {
    var that = this;
    var nowTime = new Date().getTime(); //现在时间（时间戳）
    var endTime = new Date(that.data.activityEnd).getTime(); //结束时间（时间戳）
    var time = (endTime - nowTime) / 1000; //距离结束的毫秒数
    // 获取天、时、分、秒
    let day = parseInt(time / (60 * 60 * 24));
    let hou = parseInt(time % (60 * 60 * 24) / 3600);
    let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
    let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
    day = that.timeFormin(day);
    hou = that.timeFormin(hou);
    min = that.timeFormin(min);
    sec = that.timeFormin(sec);
    that.setData({
      day: that.timeFormat(day),
      hou: that.timeFormat(hou),
      min: that.timeFormat(min),
      sec: that.timeFormat(sec)
    })
    // 每1000ms刷新一次
    if (time > 0) {
      that.setData({
        countDown: true
      })
      that.setData({
        timerName: setTimeout(function () { //这里把setInterval赋值给变量名为timer的变量
          that.countDown()
        }, 1000)
      })
    } else {
      this.getGoodsDetails()
      clearInterval(that.data.timerName);
      that.setData({
        countDown: false
      })
    }
  },
  //小于10的格式化函数（2变成02）
  timeFormat(param) {
    return param < 10 ? '0' + param : param;
  },
  //小于0的格式化函数（不会出现负数）
  timeFormin(param) {
    return param < 0 ? 0 : param;
  },
  // 授权成功的回调
  loginSucceed: function () {
    this.getUserInfo()
  },

  /**埋点 */
  setTrackerLogInfo(source) {
    let param = {
      activityId: this.data.activityId,
      resourcesId: this.data.productId,
      source: source
    }
    let merchantId = wx.getStorageSync('merchantId')
    app.setTrackerLog(merchantId, 1, 4, 2, param)
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideShareMenu({
      menus: ['shareAppMessage']
    })
    this.setData({
      activityId: options.activityId || '',
      activityBargainStarterId: options.activityBargainStarterId || '',
      originMemberId: options.shareMemberId || '', //发起会员id
      productId: options.productId || '',
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    app.getInfo().then(data => {
      if (data.data.login) {
        this.getUserInfo()
        let param = {
          activityId: this.data.activityId,
          resourcesId: this.data.productId,
          source: '砍价详情页面'
        }
        let merchantId = wx.getStorageSync('merchantId')
        app.setTrackerLog(merchantId, 1, 4, 1, param)
      } else {
        this.setData({
          authShow: true
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    // clearInterval(this.data.timerName);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearInterval(this.data.timerName);
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let activityName = '超值商品，' + this.data.nickName + '邀您来帮Ta砍一刀！'
    return {
      title: activityName || "",
      imageUrl: '/activityBargain/image/bargain_share.png',
      path: `/activityBargain/bargain/details/index?shareMemberId=${this.data.originMemberId}&activityId=${this.data.activityId}&productId=${this.data.productId}&shopId=${this.data.activityInfo.shopId}&activityBargainStarterId=${this.data.activityBargainStarterId}&isShare=1`,
    }
  }
})